from django.db import models
from utils.models import BaseModel
from ClothingStore.settings import SECRET_KEY

from itsdangerous import TimedJSONWebSignatureSerializer, SignatureExpired

TimedJSONWebSignatureSerializer_obj = TimedJSONWebSignatureSerializer(SECRET_KEY, 30 * 60)  # 以服务器key创建加密验证对象


class Area(models.Model):
    """地址构建表(省市县)"""
    name = models.CharField(max_length=20, verbose_name='地区名')
    p = models.ForeignKey('self', models.CASCADE, blank=True, null=True, verbose_name='地区关联')

    class Meta:
        verbose_name_plural = '地区'
        verbose_name = verbose_name_plural

    def __str__(self):
        return self.name

    def make_info_area(self):
        return (self.p.__str__() if self.p else '') + self.name


class UserInfo(BaseModel):
    """用户"""
    username = models.EmailField(max_length=100, verbose_name='用户名')  # 邮箱作为用户名
    password = models.CharField(max_length=100, verbose_name='密码')

    def __str__(self):
        return self.username

    class Meta:
        verbose_name_plural = '用户'
        verbose_name = verbose_name_plural

    def make_signature(self):
        """
        生成用户签名字符串
        TimedJSONWebSignatureSerializer(秘钥, 有效期(单位秒))
        Django项目中setting中自带了一个秘钥直接使用,其他地方 可以先生成一个秘钥,再使用
        :return: 签名字符串
        """
        return str(TimedJSONWebSignatureSerializer_obj.dumps({'confirm': self.pk}))[2:-1]

    def is_verify_for_signature(self, signature):
        """
        :param signature: 签名字符串
        :return: type=bool 验证结果
        """
        k = False
        try:
            data = TimedJSONWebSignatureSerializer_obj.loads(signature)
        except SignatureExpired:
            pass
        else:
            if data['confirm'] == self.pk:
                k = True
        finally:
            return k


class Address(BaseModel):
    a_name = models.CharField(max_length=30, verbose_name='地址')
    a_phone = models.CharField(max_length=11, verbose_name='手机号')
    addr = models.CharField(max_length=100, verbose_name='详细地址')
    is_default = models.BooleanField(default=False, verbose_name='是否为默认地址')
    user = models.ForeignKey(UserInfo, models.CASCADE, verbose_name='用户')

    class Meta:
        verbose_name_plural = '地址'
        verbose_name = verbose_name_plural

    def __str__(self):
        return self.a_name
